'use strict';

/**
 * @ngdoc function
 * @name jgappApp.controller:MaterialEnteringCtrl
 * @description
 * # MaterialEnteringCtrl
 * Controller of the jgappApp
 */
angular.module('jgappApp')
  .controller('MaterialEnteringCtrl', function ($scope, localStorageService, openApi, Util, $location, $routeParams, FormSubmit) {
    var id = $scope.process_id = $routeParams.id
    $scope.checkTypeList = [{
      key: "是",
      value: 1
    }, {
      key: "否",
      value: 0
    }];
    $scope.contractTypeList = [
      {
        key: "无",
        value: ""
      },
      {
        key: "采购合同",
        value: "Xm_ContractPurchase"
      },
      {
        key: "其他合同",
        value: "Xm_ContractOther"
      }
    ];
    $scope.chooseContract = function () {
      var params = $scope.param;
      if (!params.projectId || !params.contractType) {
        Util.Toast("请先选择项目与合同类型");
        return;
      }
      var projectParams = {
        formKey: params.contractType,
        fieldName: "contractNo",
        projectId: params.projectId,
        projectNo: params.projectNo
      };

      // 清掉关联的编号
      Util.savaParamForReview(params, id);
      localStorageService.set("projectParams", projectParams);
      $location.path("/project/choosedata");
    };

    $scope.chooseSupplier = function () {
      var params = $scope.param;
      var projectParams = {
        formKey: "Xm_SupplierStore",
        fieldName: "supplierNo"
      };

      // 清掉关联的编号
      Util.savaParamForReview(params, id);
      localStorageService.set("projectParams", projectParams);
      $location.path("/project/choosedata");
    };
    $scope.chooseinfo = function () {
      // 清掉关联的编号
      var params = $scope.param;
      Util.savaParamForReview(params, id);
      $location.path("/material/chooseWarehouse")
    };

    // 从清单中选
    $scope.chooseformlist = function () {
      var params = $scope.param;
      Util.savaParamForReview(params, id);
      $location.path("material/materiallist")
    };
    // 从材料计划
    $scope.chooseformMeriallist = function () {
      if (!$scope.param.warehouseId) {
        Util.Toast("请先选择仓库");
        return;
      }
      var params = $scope.param;
      Util.savaParamForReview(params, id);
      $location.path("material/materialplan/" + $scope.param.warehouseId)

    };

    // 从用料总计划
    $scope.chooseformplan = function () {
      if (!$scope.param.projectId) {
        Util.Toast("请先选择仓库");
        return;
      }

      var params = $scope.param;
      Util.savaParamForReview(params, id);

      $location.path("material/materialtotalplan/" + $scope.param.projectId)
    };


    $scope.deleteItem = function (index) {
      $scope.param.details.splice(index, 1);
      $scope.index = -1;
    };

    $scope.swipe = function (index) {
      $scope.index = index;
    }
    $scope.resetlist = function () {
      $scope.index = -1;
    }
    // 验证是否输入完整
    var checkPicker = function (data) {
      if (!data.quantity > 0) {
        Util.Toast("请输入数量");
        return;
      }
      if (!(data.price > 0 || data.price === 0)) {
        Util.Toast("请输入单价");
        return;
      }
      return true;
    };

    $scope.submit = function (operationId) {
      // 底部类型end
      var options = {};
      // 流程id
      options.id = id;
      // 根据operationId判断是草稿还是提交
      options.operationId = operationId;
      options.urlParam = openApi.materialEntering;
      options.param = angular.copy($scope.param, {});
      options.param.enteringDetails = angular.toJson($scope.param.details.map(function (item) {
        return getProperty(item)
      }))
      delete options.param.details

      FormSubmit.submit(options, $scope);
    };
    $scope.validate = function () {
      if (!$scope.param.warehouseName) {
        Util.Toast("请选择仓库名称");
        return;
      }
      if (!$scope.param.enterDate) {
        Util.Toast("请选择入库日期");
        return;
      }
      if (!$scope.param.deliverer) {
        Util.Toast("请填写交货人");
        return;
      }
      if (!$scope.param.receiver) {
        Util.Toast("请填写验收人");
        return;
      }
      if (!$scope.param.details || $scope.param.details.length === 0) {
        Util.Toast("请添加材料采购明细");
        return;
      } else {
        var validate = true
        $scope.param.details.forEach(function (item) {
          if (!checkPicker(item)) {
            validate = false
          }
        })
        if (!validate) {
          Util.Toast("请完善材料采购明细必填项");
          return;
        }
      }

      if (!$scope.validation.passvalidation) {
        Util.Toast($scope.validation.tip);
        return;
      }
      return true;
    }
    var getProperty = function (data) {
      var newData = {}
      var keys = ["purchaseId", "stuffId", "listId",
        "listNo", "name", "brand", "quantity", "remark",
        "unit", "spec", "price",
        "categoryName", "categoryId", "directOutputting"
      ]
      keys.forEach(function (key) {
        newData[key] = data[key]
      })
      newData.soruceType = 4
      return newData
    }
    var init = function () {
      // 获取回显的详细信息
      Util.getDetailData(id, function (data) {
        $scope.param = data;
        if (typeof $scope.param.taxInclusive === "undefined") {
          $scope.param.taxInclusive = 1;
        }

        var list1 = localStorageService.get("materialslist")
        var list2 = localStorageService.get("materialsplan")
        var list3 = localStorageService.get("materialsTotalplan")
        localStorageService.remove("materialsTotalplan")
        localStorageService.remove("materialsplan")
        localStorageService.remove("materialslist")
        const selectList = list3 || list2 || list1 || []
        var count = 0
        $scope.param.details = selectList.reduce(function (arr, current, index) {
          const findItem = arr.find(function (item) {
            return item.pkId === current.pkId
          })
          if (!findItem) {
            current.price = current.price || 0;
            current.directOutputting = 0;
            arr.push(current)
          } else {
            count++
          }
          return arr
        }, $scope.param.details || [])
        if (count > 0) {
          Util.Toast((selectList.length - count) + "条数据添加成功," + count + "条重复数据未添加", { time: 4000 })
          count = 0
        }
      });
    };
    // 初始化
    init();
  });
